from firstDjango.exceptions import FormException
from index.common.tool import DATE_TIME_FMT
from index.models import UserInfo
from index.models import ExtendUserInfo


# 创建用户
from index.protocol.user_protocol import UpdateUserInfo


def create_user(username, password, gender):
    user = UserInfo(username=username, password=password, gender=gender)
    user.save()
    return user.id


# 登录
def login(username, password):
    try:
        user = UserInfo.objects.get(username=username, password=password)
        return user
    except UserInfo.DoesNotExist:
        raise FormException("用户名或密码错误❌")



# 通过姓名查找用户
def get_user_by_name(username):
    # user_exist = UserInfo.objects.filter(username=username).exists()
    data = UserInfo.objects.filter(username=username)
    if data:
        user = list(data)[0]
        return user.id
    else:
        return False


# 添加额外信息
def add_ExtendUserInfo(user_id, signature, nickname):
    extend_userInfo = ExtendUserInfo(user_id=user_id, signature=signature, nickname=nickname)
    extend_userInfo.save()
    return user_id


# 判断额外信息是否存在
def judge_ExtUserInfo(user_id):
    exist = ExtendUserInfo.objects.filter(user_id=user_id).exists()
    return exist


# 通过id获取用户信息
def getUserInfo(user_id):
    try:
        userInfo = UserInfo.objects.select_related("extenduserinfo").get(id=user_id)
    except UserInfo.DoesNotExist:
        raise FormException("用户(id=%s)不存在" % user_id)

    return userInfo


# 更新用户信息
def update_userInfo(user_id, update_info: UpdateUserInfo):
    user: UserInfo = UserInfo.objects.select_related("extenduserinfo").get(id=user_id)
    if update_info.gender is not None:
        user.gender = update_info.gender

    extend_info: ExtendUserInfo = getattr(user, 'extenduserinfo', ExtendUserInfo(user_id=user_id))
    if update_info.signature is not None:
        extend_info.signature = update_info.signature
    if update_info.nickname is not None:
        extend_info.nickname = update_info.nickname
    if update_info.avatar is not None:
        extend_info.avatar = update_info.avatar
    extend_info.save()
    if not hasattr(user, 'extenduserinfo'):
        user.extenduserinfo = extend_info

    user.save()

